package org.example.rabbitmq.server.route.strategy.impl;

import org.example.rabbitmq.config.MultiQueueProperties;
import org.example.rabbitmq.server.route.strategy.RouteStrategy;
import org.example.rabbitmq.vo.RoutingKey;
import org.example.rabbitmq.vo.TenantId;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinRouteStrategy implements RouteStrategy {
    @Autowired
    MultiQueueProperties multiQueueProperties;
    AtomicInteger counter = new AtomicInteger(1);

    @Override
    public RoutingKey route(TenantId tenantId) {
        int v = counter.getAndUpdate((prev) -> {
            prev++;
            if (prev > multiQueueProperties.getQueueSize()) {
                return prev - multiQueueProperties.getQueueSize();
            } else {
                return prev;
            }
        });
        return new RoutingKey(multiQueueProperties.getRoutingKeyWithIndex(v));
    }
}